from typing import Annotated, Optional
from fastapi import HTTPException, Depends
from fastapi.security import OAuth2PasswordBearer
from passlib.context import CryptContext
from pydantic.v1 import BaseModel
from jose import jwt
from sqlalchemy.orm import Session

from db import get_db
from models import User

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/user/token")
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
SECRET_KEY = "6666"
ALGORITHM = "HS256"

class TokenData(BaseModel):
    uid: int | None = None

class UserPublic(BaseModel):
    id: int
    phone: str
    name: str
    avatar: str
    class Config:
        orm_mode = True

class UserInDB(UserPublic):
    hashed_password: str

    class Config:
        orm_mode = True

def get_user(db: Session, uid: int):
    user = db.query(User).filter(User.id == uid).first()
    if user:
        return UserPublic.from_orm(user)
    return None

async def get_current_active_user(token: Annotated[str, Depends(oauth2_scheme)], db: Session = Depends(get_db)):
    print(token)
    credentials_exception = HTTPException(
        status_code=401,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        uid: str = payload.get("user_id")
        print("uid", uid)
        if uid is None:
            raise credentials_exception
        token_data = TokenData(uid=uid)
    except jwt.JWTError:
        raise credentials_exception
    user = get_user(db, uid=token_data.uid)
    print(user)
    if user is None:
        raise credentials_exception
    return user

async def get_current_active_user(current_user: Annotated[User, Depends(get_current_active_user)]):
    print(current_user)
    return current_user